/*
 *   项目名称：rpc-demo
 *   文件名称：com.xiaolon.rpc.protocol.ProtocolMessageEncoder
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/9
 *
 */
package com.xiaolon.rpc.protocol;

import com.xiaolon.rpc.serializer.Serializer;
import com.xiaolon.rpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/*
 * 类描述：ProtocolMessageEncoder
 * 消息编码器
 */
public class ProtocolMessageEncoder {

    /**
     * 消息编码
     * @param protocolMessage
     * @return
     * @throws Exception
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        if(protocolMessage == null || protocolMessage.getHeader() == null) {
            return Buffer.buffer();
        }

        ProtocolMessage.Header header = protocolMessage.getHeader();

        // 以此向缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

        // 获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if(serializerEnum == null){
            throw new RuntimeException("序列化协议不存在");
        }

        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());

        // 写入body长度和数据
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        return buffer;
    }
}
